<script setup>
import { computed, ref, watch, provide } from 'vue'
import { message } from 'ant-design-vue'
import { number } from 'echarts'

const emits = defineEmits(['update:modelValue'])
const props = defineProps({
  // 选择的表格组件
  component: { type: Object, default: () => ({}) },
  // 选择数据个数
  sltLength: { type: Number, default: 1 },
  // 回显键名的映射
  fieldNames: { type: Object, default: () => ({ name: 'name', id: 'id' }) },
  // 双向绑定数据
  modelValue: { type: [String, Number], default: '' },
  // 回显名称数据
  nameValue: { type: String, default: '' },
  // 获取选中的数据
  getRows: { type: Function, default: () => {} },
  // 表格默认筛选条件
  params: { type: Object, default: () => ({}) },
  // 禁用
  disabled: { type: Boolean, default: false },
  //绑定状态
  deviceStatus: { type: number, default: 0 }
})
// 已选择数据id数组
const selectedRowKeys = ref([])
// 修改选择项
const changeRowSelect = (_keys, rows) => {
  sltRows.value = rows
  const ids = rows.map((item) => item[props.fieldNames.id])
  selectedRowKeys.value = ids
  props.getRows && props.getRows(sltRows.value)
  emits('update:modelValue', ids.join(','))

  // 获取选中的农机数据，并传递给父组件
  const selectedMachine = rows[0] // 假设选择的是单个农机
  if (selectedMachine) {
    // 传递完整的选中农机数据对象给父组件
    emits('selected-machine', selectedMachine)
  }
}
// 选择配置
const rowSelection = computed(() => ({
  type: props.sltLength === 1 ? 'radio' : 'checkbox',
  selectedRowKeys: selectedRowKeys.value,
  onChange: changeRowSelect
}))

// 用于选择的表格组件
const TableSlt = computed(() => props.component)
// 显示隐藏
const show = ref(false)
// 打开选择弹窗
const open = () => {
  show.value = true
}
// 已选择数据列
const sltRows = ref([])
// 标签关闭回调
const closeTag = (i) => {
  sltRows.value.splice(i, 1)
  const ids = sltRows.value.map((item) => item[props.fieldNames.id])
  selectedRowKeys.value = ids
  props.getRows && props.getRows(sltRows.value)
  emits('update:modelValue', ids.join(','))
}
// 监听显示名称变化，主要是回显逻辑
watch(
  () => props.nameValue,
  () => {
    selectedRowKeys.value = [Number(props.modelValue) || props.modelValue]
    if (props.nameValue) {
      sltRows.value = [
        {
          [props.fieldNames.id]: Number(props.modelValue) || props.modelValue,
          [props.fieldNames.name]: props.nameValue
        }
      ]
    } else {
      sltRows.value = []
    }
  },
  { immediate: true }
)

provide('fieldNames', props.fieldNames)
provide('rowSelection', rowSelection)
provide('changeSelectRows', (row) => {
  if (props.sltLength === 1) {
    sltRows.value = []
    selectedRowKeys.value = []
    changeRowSelect(null, [row])
    return
  }
  const _index = selectedRowKeys.value.indexOf(row[props.fieldNames.id])
  if (_index !== -1) {
    sltRows.value.splice(_index, 1)
    selectedRowKeys.value.splice(_index, 1)
    return
  }
  if (selectedRowKeys.value.length === props.sltLength) {
    const label = sltRows.value.map((item) => item[props.fieldNames.name]).join('、')
    message.warning(`最多选择${props.sltLength}条数据，已选择：${label}`)
    return
  }
  const rows = [...sltRows.value, row]
  changeRowSelect(null, rows)
})

const afterOpenChange = () => {}
</script>

<template>
  <div>
    <div class="tags" v-if="sltRows.length > 0">
      已选择：<ATag
        :closable="!props.disabled"
        color="success"
        v-for="(item, i) of sltRows"
        :key="item[props.fieldNames.id]"
        @close="closeTag(i)"
      >
        {{ item[props.fieldNames.name] }}
      </ATag>
    </div>
    <AButton type="primary" @click="open" v-if="!props.disabled"> 从列表选择 </AButton>
    <a-drawer
      :maskClosable="false"
      :closable="false"
      destroyOnClose
      v-model:open="show"
      width="1400px"
      class="custom-class"
      root-class-name="root-class-name"
      title="选择数据"
      placement="right"
      @after-open-change="afterOpenChange"
    >
      <div style="display: flex; flex-direction: column">
        <a-alert
          :message="`请点击数据选择${
            sltLength === 99999 ? '' : `，最多可选择${props.sltLength}条数据`
          }`"
          banner
          style="margin-bottom: 20px"
        />
        <div class="tags" v-if="sltRows.length > 0" style="margin-bottom: 20px">
          已选择：
          <ATag
            closable
            color="success"
            v-for="(item, i) of sltRows"
            :key="item[props.fieldNames.id]"
            @close="closeTag(i)"
          >
            {{ item[props.fieldNames.name] }}
          </ATag>
        </div>
        <div style="flex: 1; overflow: hidden">
          <TableSlt :params="props.params" />
        </div>
      </div>
      <template #footer>
        <AButton
          :type="sltRows.length > 0 ? 'primary' : 'default'"
          @click="show = false"
          style="width: fit-content"
        >
          {{ sltRows.length > 0 ? '确认' : '关闭' }}
        </AButton>
      </template>
    </a-drawer>
  </div>
</template>

<style lang="scss" scoped>
.tags {
  margin: 0 0 10px;
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 5px 3px;
  color: #52c41a;
}
</style>
